package com.dckj.auto.common.interceptor;

import com.alibaba.fastjson.JSONArray;
import com.dckj.auto.common.utils.JsonUtils;
import com.dckj.auto.common.utils.SendMsgUtil;
import com.dckj.auto.controller.help.UserMenuHelp;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Conntroller 上的注解拦截
 */
public class AuthorityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        AuthorityAnnotation annotation = method.getMethod().getAnnotation(AuthorityAnnotation.class);
        if(null != annotation){
            JSONArray jsonArray = UserMenuHelp.userAuthMenu(request,1);
            if(null == jsonArray){
                SendMsgUtil.sendJsonMessage(response, JsonUtils.error(101,"没有此项操作权限"));
                return false;
            }
            String auto = jsonArray.toString();
            if (!auto.contains(annotation.authority())){
                SendMsgUtil.sendJsonMessage(response, JsonUtils.error(101,"没有此项操作权限"));
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }




}
